#!/usr/bin/env python
# -*- coding: utf-8 -*-       
from django import template
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode

from datetime import timedelta

from siteutils.units import convert
from siteutils.language import translate

register = template.Library()

def truncate_chinese_words(s, num):
    length = int(num)
    try:
        words = s.decode('ascii')
        return template.defaultfilters.truncatewords(s, length)
    except:
        pass
    words = s
    if len(words) > length:
        words = words[:length]
        if not words[-1].endswith('...'):
            words += ('...')
    return words

register.filter(truncate_chinese_words)   

def divide(a, b):
    a = float(a)
    b = float(b)
    return a/b

register.filter(divide)

def timezone(value, offset=0):
    return value and value + timedelta(hours=offset)

register.filter(timezone)

def cctimesince(value, arg=None):
    """Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
    from django.utils.timesince import timesince
    if not value:
        return u''
    try:
        if arg:
            str = timesince(value, arg)
        else:
            str = timesince(value)
        old_ts_arr = str.split(",")
        new_ts_arr = []
        for s in old_ts_arr:
            arr2 = s.strip().split(" ")
            num = arr2[0]
            time = translate(arr2[1])
            if not isinstance(time, unicode):
                time = unicode(time,'utf-8')
            new_ts_arr.append(u" ".join( (num,time) ))
        return u",".join(new_ts_arr)
    except (ValueError, TypeError):
        import logging
        logging.exception("error in cctimesince")
        return u''

cctimesince.is_safe = False
register.filter(cctimesince)

def _u(value):
    return convert(value)

register.filter(_u)

def unescape(value):
    return mark_safe(force_unicode(value).replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"')\
    .replace('&#39;', "'").replace('&amp;', '&'))

register.filter(unescape)

def main():
    pass

if __name__ == '__main__':
  main()
